#include<exeRecorder.h>
ExeRecorder::ExeRecorder(std::string path):Recorder(path){}
ExeRecorder::~ExeRecorder(){}

//读取指定进程的文件数据
void ExeRecorder::read(int pid){
    while(flag){
        //std::cerr<<"ezbshuo\n";

        sem_a_down(pid);
        std::cerr<<"read\n";
        std::string filename = path+"/middle"+std::to_string(pid)+".txt";//executor要打开的文件名
        std::string line;
        std::ifstream inFile(filename);
        if (!inFile) {
            std::cerr << "无法打开文件！" << std::endl;
            return;
        }
        std::getline(inFile, line);
        clear(pid);//将文件内容删除
        //解锁
        sem_b_up(pid);
        //std::cerr<<"ejiesuo\n";
        if(flag == 0)return;
        if(line == "end"){
            std::string temp;
            temp = "/a"+std::to_string(pid);
            sem_unlink(temp.c_str());
            temp = "/b"+std::to_string(pid);
            sem_unlink(temp.c_str());
            break;
        }
        callback(this, line);
    }
}
bool ExeRecorder::write(std::string front,std::string name1, std::string name2){
    mx.lock();
    std::string filename = path+"/final.txt";//executor要打开的文件名
    std::fstream outfile(filename,std::ios::out | std::ios::app);  //打开文件
    if (!outfile.is_open()) {          // 检查是否成功打开
        std::cout << "Failed to open file." << std::endl;
        return false;
    }
    std::string temp = front+slice9+name1+slice10+name2+slice11+"\n";
    outfile<<temp;
    outfile.close();
    mx.unlock();
    return true;
}
void ExeRecorder::setCallBack(std::function<void(ExeRecorder*, std::string)> callback){
    this->callback = callback;
}
void ExeRecorder::run(std::vector<int> pids){
    this->pids = pids;
    flag = 1;
    for(int i = 0; i <pids.size(); i++){
        threads.emplace_back(std::bind(&ExeRecorder::read, this, pids[i]));
    }
    for(int i = 0; i <pids.size(); i++){
        threads[i].detach();
    }
    std::cerr<<"runchu\n";
}
void ExeRecorder::clear(int pid){
    std::string filename = path+"/middle"+std::to_string(pid)+".txt";
    std::ofstream truncateFile(filename, std::ios::trunc);
	truncateFile.close();
}
// void  ExeRecorder::stop(){
//     flag = 0;
//     for(int i = 0; i <pids.size(); i++){
//         sem_a_up(pids[i]);
//         sem_b_up(pids[i]);
//     }
// }